package com.skyline.courier.mq.provider.rabbitmq;

import java.util.HashMap;
import java.util.Map;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.QueueingConsumer.Delivery;
import com.skyline.courier.mq.MessageHandler;
import com.skyline.courier.mq.Protocol;

/**
 * 消息包处理类，封装了消息处理接口
 * 
 * @author wuqh
 * 
 */
public class DeliveryHandler {
	private final MessageHandler handler;
	private final Protocol<?, byte[]> protocol;

	public DeliveryHandler(MessageHandler handler, Protocol<?, byte[]> protocol) {
		this.handler = handler;
		this.protocol = protocol;
	}

	public void handleMessage(Channel channel, Delivery delivery) {
		String key = delivery.getEnvelope().getRoutingKey();
		byte[] data = delivery.getBody();

		Map<String, Object> context = new HashMap<String, Object>(2, 1f);
		context.put("channel", channel);
		context.put("delivery", delivery);

		if (handler != null) {
			Object message = protocol.decode(data);
			handler.handle(key, message, context);
		}
	}
}
